package org.sdfc.model

import org.sdfc.model.attr.key.KeyAttribute
import org.sdfc.model.attr.key.KeyAttributeOps

import scala.collection.immutable.Set
import scala.collection.immutable.HashMap

import com.documentum.fc.client.IDfTypedObject

/** Naive representation of a type as a sequence of KeyAtttributes
 *  of distinct names.
 */
class SimpleType private (
  /** The KeyAttributes making up this, kept in order. */
  val attrs : Vector[KeyAttribute[Any]],
  /** Map associating names to KeyAttributes. */
  nameMap : Map[String, KeyAttribute[Any]]
) {
  
  /** Constructs an empty SimpleType.<br/>
   *  Useful in combination with + to constructs a complex SimpleType by aggregation.
   */
  def this() = this( Vector[KeyAttribute[Any]](), HashMap[String, KeyAttribute[Any]]() )
  
  
  /** Combines this and the given KeyAttribute <code>attr</code> into a new SimpleType.
   *  Unless there is a name collision, in which case it throws an Exception.
   */
  def +(attr : KeyAttribute[Any]) : SimpleType =
    if ( nameMap.contains(attr.name) ) error("SimpleType: already defines an attribute named " + attr.name )
    else new SimpleType( attrs :+ attr, nameMap + (attr.name -> attr) )
  
}


object SimpleType {
  
  /** Extracts the SimpleType of a given IDfTypedObject.
   */
  def extract(obj : IDfTypedObject) : SimpleType =
    (0 until obj.getAttrCount).foldLeft(new SimpleType) {
      (acc : SimpleType, i : Int) => acc + KeyAttributeOps.convert(obj.getAttr(i))
    }
  
}